package com.xujie.chat.client.handler;

import com.xujie.chat.message.MessageType;
import com.xujie.chat.message.MsgHeader;
import com.xujie.chat.message.MyMessage;
import com.xujie.chat.message.NettyConstant;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.ReadTimeoutException;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Xujie
 * @since 2024/12/28 22:23
 **/


public class HeartBeatReqHandler extends ChannelInboundHandlerAdapter {
    private static final Logger LOG = LoggerFactory.getLogger(HeartBeatReqHandler.class);

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt == IdleStateEvent.FIRST_WRITER_IDLE_STATE_EVENT) {
            MyMessage heartBeat = buildHeatBeat(ctx.channel().attr(NettyConstant.CHANNEL_ID_KEY).get());
            LOG.debug("写空闲，发出心跳报文维持连接： {}", heartBeat);
            ctx.writeAndFlush(heartBeat);
        }
        super.userEventTriggered(ctx, evt);
    }

    private MyMessage buildHeatBeat(String clientId) {
        MyMessage message = new MyMessage();
        MsgHeader msgHeader = new MsgHeader();
        msgHeader.setType(MessageType.HEARTBEAT_REQ.value());
        msgHeader.setClientId(clientId);
        message.setMyHeader(msgHeader);
        return message;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        MyMessage message = (MyMessage) msg;
        /*是不是心跳的应答*/
        if (message.getMyHeader() != null
                && message.getMyHeader().getType() == MessageType.HEARTBEAT_RESP.value()) {
            LOG.debug("收到服务器心跳应答，服务器正常：{}", ctx.channel().id().asLongText());
            ReferenceCountUtil.release(msg);
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        if (cause instanceof ReadTimeoutException) {
            LOG.warn("服务器长时间未应答，关闭链路");
            //ctx.close();
        }
        super.exceptionCaught(ctx, cause);
    }
}
